package com.zoe.onelink.logging.trace.feign.processor;

import ch.qos.logback.core.joran.util.beans.BeanDescriptionFactory;
import com.zoe.onelink.logging.trace.feign.client.OnelinkFeignTraceClient;
import feign.Client;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.cloud.netflix.ribbon.SpringClientFactory;
import org.springframework.cloud.openfeign.ribbon.CachingSpringLoadBalancerFactory;
import org.springframework.cloud.openfeign.ribbon.LoadBalancerFeignClient;

/**
 * <p>标题: </p>
 * <p>描述: </p>
 * <p>版权: Copyright (c) 2022</p>
 * <p>公司: 智业软件股份有限公司</p>
 *
 * @version: 1.0
 * @author: ruansheng
 * @date: 2022-09-14
 */
@RequiredArgsConstructor
public class OnelinkFeignContextBeanPostProcessor implements BeanPostProcessor {

    // private final CachingSpringLoadBalancerFactory cachingFactory;
    // private final SpringClientFactory clientFactory;
    private final BeanFactory beanFactory;

    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        if (bean instanceof LoadBalancerFeignClient) {
            Client delegate = ((LoadBalancerFeignClient) bean).getDelegate();
            if (delegate instanceof OnelinkFeignTraceClient) {
                return bean;
            }
            return new LoadBalancerFeignClient(new OnelinkFeignTraceClient(delegate),
                    this.beanFactory.getBean(CachingSpringLoadBalancerFactory.class),
                    this.beanFactory.getBean(SpringClientFactory.class));
        }
        return bean;
    }
}
